/*
  悬浮控件
  用于任意位置弹窗，包括Toast
  类似Android中的popup window
  如果不想传入context，可使用第三方库
 */


import 'package:flutter/material.dart';

class Toast {
  static show(BuildContext context, String msg) {
    // 创建布局
    OverlayEntry overlayEntry = OverlayEntry(builder: (context){
      return Align(
        alignment: Alignment.center,
        child: Material( // 一定要有样式
          color: Colors.transparent,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: Colors.black12
            ),
            padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            child: Text(msg, style: TextStyle(color: Colors.white, fontSize: 18),),
          ),
        ),
      );
    });
    // 添加
    Overlay.of(context)!.insert(overlayEntry);
    // 两秒后消失
    Future.delayed(Duration(seconds: 2)).then((value) =>
      overlayEntry.remove()
    );
  }
}

void main(){
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('OverLay')),
        body: HomePage(),
      ),
    )
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TextButton(onPressed: (){
      Toast.show(context, '开始倒计时');
    }, child: Text('toast'));
  }
}
